window.onload = function () {
    select();
    const btn = document.getElementById("create");
    btn.onclick = function () {
        document.getElementById("outPw").replaceChild(document.createTextNode(make(document.getElementById("pwLength").options[document.getElementById("pwLength").selectedIndex].value, document.getElementById("punctuate").checked)), document.getElementById("outPw").firstChild);
    }
}

function select(){
    let i;
    const id = [];
    for (i = 0; i<121; i++){
        id[i] = i+8
    }
    const select = document.getElementById("pwLength");
    for(i = 0; i<id.length; i++){
        const option = document.createElement("option");
        option.setAttribute("value",id[i]);
        option.appendChild(document.createTextNode(id[i]));
        select.appendChild(option);
    }
    select.options[8].selected=true;
}

function createPw(length, punctuate) {
    let i;
    const punctuates = "()_-~@#$%^&*+=`[]{}:.,?";
    const pwArray = [];

    //随机生成字母
    for (i = 0; i < length; i++) {
        if (Math.round(Math.random()) === 0) {
            pwArray[i] = String.fromCharCode(Math.floor(Math.random() * 26) + 65);
        } else {
            pwArray[i] = String.fromCharCode(Math.floor(Math.random() * 26) + 97);
        }
    }
    //随机替换数字
    const maxNum = length - 2;
    const numLength = Math.floor(Math.random() * maxNum) + 1;
    for (i = 0; i < numLength; i++) {
        pwArray[Math.floor(Math.random() * length)] = Math.floor(Math.random() * 10);
    }
    //随机替换标点
    if (punctuate) {
        const punNum = punctuates.length;
        const maxPun = length - 3;
        const punLength = Math.floor(Math.random() * maxPun) + 1;
        for (i = 0; i < punLength; i++) {
            pwArray[Math.floor(Math.random() * length)] = punctuates.charAt(Math.floor(Math.random() * punNum));
        }
    }

    return pwArray.join("");
}

function make(length, punctuate) {
    let pattern;
    if (punctuate) {
        eval("pattern = /^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*)(?=.*\\W.*).{" + length + "}$/;");
    } else {
        eval("pattern = /^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{" + length + "}$/;");
    }
    let pwStr = "";
    let check = !1;
    while (!check) {
        pwStr = createPw(length, punctuate);
        if (pattern.exec(pwStr)) {
            check = !0;
        }
    }
    return pwStr;
}
